<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        position: relative;
        width: 200px;
        height: 200px;
      }

      .item {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: linen;
        opacity: 0;
        transition: transform 1s, opacity 1s;
      }

      .active {
        opacity: 1;
        z-index: 2000;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="container">
        <div
          ref="itemRef"
          v-for="(item, i) in items"
          :key="item"
          class="item"
          @click="handleClick(item)"
        >
          {{ item }}
        </div>
      </div>
      <div v-show="flipping === false">
        <button @click="handleSwitch('pre')">pre</button>
        <button @click="handleSwitch('next')">next</button>
      </div>
    </div>

    <script type="module">
      import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.esm.browser.js'

      const vm = new Vue({
        el: '#app',
        data() {
          return {
            currentIndex: 0,
            items: [1, 2, 3, 4],
            flipping: false,
          }
        },
        mounted() {
          // 默认设置第一项为活跃的
          this.$refs.itemRef[0].classList.add('active')
        },
        methods: {
          handleClick(item) {
            console.log(item)
          },
          handleSwitch(type) {
            if (this.flipping) return
            this.flipping = true
            let degree = type == 'next' ? 180 : -180
            let itemsLen = this.items.length
            const items = this.$refs.itemRef
            // 翻转当前项
            const currentItem = items[this.currentIndex]
            currentItem.classList.remove('active')
            currentItem.style.transform = `rotateX(${degree}deg)`
            // 设置下一项的索引
            let nextIndex = 0
            if (degree > 0) {
              nextIndex =
                this.currentIndex + 1 === itemsLen ? 0 : this.currentIndex + 1
            } else {
              const endIndex = itemsLen - 1
              nextIndex =
                this.currentIndex - 1 < 0 ? endIndex : this.currentIndex - 1
            }
            this.currentIndex = nextIndex
            // 将下一项设置为活跃的
            const nextItem = items[nextIndex]
            nextItem.classList.add('active')
            // 设置完以后，清除所有元素的旋转样式
            setTimeout(() => {
              items.forEach((element) => {
                element.style.transform = 'rotateX(0deg)'
                this.flipping = false
              })
            }, 1000)
          },
        },
      })
    </script>
  </body>
</html>
